<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      @returnBack="returnBack"
      :needReturn="!$route.query.processInstanceId"
      title="机构信息"
      :btnList="fullInfo.btnList"
    >
      <template v-slot:full-button>
        <el-button
            v-if="
              $permission('orgInfo:approve') &&
              orgInfo.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_org_check_approval == 1
            "
            :plain="true"
            @click="approve"
            >批准</el-button
          >
          <el-button
            v-if="
              $permission('orgInfo:reject') &&
              orgInfo.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_org_check_approval == 1
            "
            :plain="true"
            @click="reject"
            >驳回</el-button
          >
          <el-button
            v-if="
              $permission('orgInfo:refuse') &&
              orgInfo.data.checkStatus === 1 &&
              $store.state.permission.systemConfig
                .allow_slip_org_check_approval == 1
            "
            :plain="true"
            @click="refuse"
            >拒绝</el-button
          >
      </template>

      <div class="model-panel">
        <div class="model-panel-title">
          <p>机构信息</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="orgInfo" :labelWidth="labelWidth">
            <template v-slot:basic-province>
              <address-info :data="orgAddress"></address-info>
            </template>
          </basic-information>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>营业执照</p>
        </div>
        <div class="model-panel-body">
          <basic-information
            :info="certificateOfBusinessInfo"
            :labelWidth="labelWidth"
          >
            <template v-slot:basic-licenseFilePath>
              <ele-gallery
                v-if="certificateOfBusinessInfo.data.licenseFilePath"
                :lazy="true"
                :remove-fn="handleRemove"
                :size="150"
                :source="certificateOfBusinessInfo.data.licenseFilePaths"
                title="营业执照"
              />
              <span v-else>-</span>
            </template>
          </basic-information>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>第三类医疗器械经营许可证</p>
        </div>
        <div class="model-panel-body">
          <basic-information
            :info="businessLicenseInfo"
            :labelWidth="labelWidth"
          >
            <template v-slot:basic-licenseFilePath>
              <ele-gallery
                v-if="businessLicenseInfo.data.licenseFilePath"
                :lazy="true"
                :remove-fn="handleRemove"
                :size="150"
                :source="businessLicenseInfo.data.licenseFilePaths"
                title="第三类医疗器械经营许可证"
              />
              <span v-else>-</span>
            </template>
          </basic-information>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>第二类医疗器械经营备案凭证</p>
        </div>
        <div class="model-panel-body">
          <basic-information :info="businessRecordCertificate">
            <template v-slot:basic-licenseFilePath :labelWidth="labelWidth">
              <ele-gallery
                v-if="businessRecordCertificate.data.licenseFilePath"
                :lazy="true"
                :remove-fn="handleRemove"
                :size="150"
                :source="businessRecordCertificate.data.licenseFilePaths"
                title="第二类医疗器械经营备案凭证"
              />
              <span v-else>-</span>
            </template>
          </basic-information>
        </div>
      </div>
    </NewFullScreen>
  </div>
</template>

<script setup name="pendCheckOrgInfoDetail">
import BasicInformation from '@/components/BasicInformation/index'
import AddressInfo from '@/components/AddressInfo/index'
import {
  getOrgInfoCheck,
  orgInfoApproved,
  orgInfoRefuse,
  orgInfoReject,
  getOrgInfoCheckDifference,
} from '@/api/base'
import EleGallery from '@/components/UploadImg/eleGallery'
import citys from '@/assets/js/city.js'
import _ from 'lodash'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const props = defineProps(['visible', 'id'])

const fullInfo = reactive({
  btnList: [{ value: 'button', type: 'slot' }],
})
const orgInfo = reactive({
  diffData: {},
  data: {},
  fieldList: [
    { label: '机构名称', value: 'name' },
    { label: '地址', value: 'province', type: 'slot', diffValue: 'orgAddress' },
    { label: '详细地址', value: 'address' },
    { label: '联系电话', value: 'phone' },
  ],
})
const certificateOfBusinessInfo = reactive({
  diffData: {},
  data: {},
  fieldList: [
    { label: '证书编号', value: 'certificateNumber' },
    { label: '注册地址', value: 'registeredAddress' },
    { label: '公司类型', value: 'companyTypeValue' },
    {
      label: '注册资本(万元)',
      value: 'registeredCapital',
      formatter: proxy.$fn.TripartiteMethod,
    },
    { label: '成立时间', value: 'establishedDate' },
    { label: '经营范围', value: 'businessScope' },
    { label: '发证机关', value: 'issuingAuthority' },
    { label: '发证日期', value: 'issuingDate' },
    { label: '营业开始日期', value: 'startDate' },
    { label: '营业截止日期', value: 'endDate' },
    { label: '营业执照', value: 'licenseFilePath', type: 'slot' },
  ],
})
const businessLicenseInfo = reactive({
  diffData: {},
  data: {},
  fieldList: [
    { label: '证书编号', value: 'certificateNumber' },
    { label: '企业名称', value: 'companyName' },
    { label: '注册地址', value: 'registeredAddress' },
    { label: '法定代表人', value: 'legalRepresentative' },
    { label: '企业负责人', value: 'responsiblePersons' },
    { label: '质量管理人', value: 'qualityManager' },
    { label: '经营范围', value: 'businessScope' },
    { label: '发证机关', value: 'issuingAuthority' },
    { label: '发证日期', value: 'issuingDate' },
    { label: '许可期限开始日期', value: 'startDate' },
    { label: '许可期限截止日期', value: 'endDate' },
    { label: '经营许可证', value: 'licenseFilePath', type: 'slot' },
  ],
})
const businessRecordCertificate = reactive({
  diffData: {},
  data: {},
  fieldList: [
    { label: '备案编号', value: 'recordNumber' },
    { label: '备案日期', value: 'recordDate' },
    { label: '企业名称', value: 'businessName' },
    { label: '住所', value: 'registeredAddress' },
    { label: '经营场所', value: 'businessAddress' },
    { label: '库房地址', value: 'warehouseAddress' },
    { label: '经营方式', value: 'businessTypeValue' },
    { label: '法定代表人', value: 'legalRepresentative' },
    { label: '企业负责人', value: 'responsiblePersons' },
    { label: '经营范围', value: 'businessScope' },
    { label: '备注', value: 'remark' },
    { label: '证书附件', value: 'licenseFilePath', type: 'slot' },
  ],
})
const labelWidth = ref('140px')
const showUpdate = ref(false)
const type = ref('update')
const orgId = ref(proxy.$store.state.user.userInfo.user.orgId || '')
const orgAddress = ref([])
const needReturn = ref(false)
const showBtn = ref(true)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => props.id,
  (newVal) => {
    init()
  },
  {
    immediate: true,
    deep: true,
  }
)

function reject() {
  btnFlow(orgInfo.data, 'reject')
}
// 按钮审批原因弹窗
function btnFlow(row, code) {
  let currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = orgInfoReject
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = orgInfoRefuse
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderIds: [row.id],
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          init()
        }
      })
    })
}
//确认
function approve() {
  const ids = [orgInfo.data.id]
  orgInfoApproved({orderIds: ids}).then((resp) => {
    if (resp && resp.success) {
      init()
    }
  })
}
//拒绝
function refuse() {
  btnFlow(orgInfo.data, 'refuse')
}

function returnBack() {
  emit('returnBack', false)
}
const getCity = (citys, n, orgAddress) => {
  let address = ''
  let data = orgAddress
  if (citys.length <= 0 || n >= data.length) return
  let index = _.findIndex(citys, function (o) {
    return o.value === data[n]
  })
  if (index !== -1) {
    address += citys[index].label
    if (citys[index]['children']) {
      address += getCity(citys[index]['children'], n + 1, data)
    }
  }
  return address
}
function getDiff() {
  getOrgInfoCheckDifference(orgInfo.data).then((res) => {
    if (res && res.success && res.data) {
      orgInfo.diffData = res.data
      let { province, city, county } = orgInfo.diffData
      let orgAddress = []
      if (province) {
        orgAddress.push(province)
      }
      if (city) {
        orgAddress.push(city)
      }
      if (county) {
        orgAddress.push(county)
      }
      orgInfo.diffData.orgAddress = getCity(citys, 0, orgAddress)
      certificateOfBusinessInfo.diffData = res.data
      businessLicenseInfo.diffData = res.data
      businessRecordCertificate.diffData = res.data
    }
  })
}
function init() {
  getOrgInfoCheck(props.id).then((res) => {
    if (res) {
      orgInfo.data = res.data.org

      let { province, city, county } = orgInfo.data
      if (province) {
        orgAddress.value.push(province)
      }
      if (city) {
        orgAddress.value.push(city)
      }
      if (county) {
        orgAddress.value.push(county)
      }
      certificateOfBusinessInfo.data = res.data.businessLicense
      businessLicenseInfo.data = res.data.businessPermit
      businessRecordCertificate.data = res.data.businessRecordCertificate
      getDiff()
    }
  })
}

function handleRemove(index) {
  // if (this.multiple) {
  //   const data = [...computedValues.value];
  //   data.splice(index, 1);
  //   emit("input", data || []);
  // } else {
  //   emit("input", null);
  // }
}
</script>

<style scoped></style>
